//
//  HD_LiDa_Playermanager.m
//  HDMusicDemo
//
//  Created by Lida on 2017/8/14.
//  Copyright © 2017年 Lida. All rights reserved.
//

#import "HD_LiDa_Playermanager.h"
#import "HD_LiDa_PlayerTool.h"
#import "AppDelegate.h"
#import <MediaPlayer/MediaPlayer.h>
@implementation HD_LiDa_Playermanager

singleton_implementation(HD_LiDa_Playermanager);

-(instancetype)init
{
    self = [super init];
    if (self) {
        //设置音乐后台播放的会话类型
        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *error = nil;
        [session setCategory:AVAudioSessionCategoryPlayback error:&error];
        if (error) {
            NSLog(@"%s %@", __func__, error);
        }
        BOOL success = [session setActive:YES error:nil];
        if (!success)
        {
            NSLog(@"Error setting category: %@", [error localizedDescription]);
        }
        
        //监听耳机的插入，拔出
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeListenerCallback:)   name:AVAudioSessionRouteChangeNotification object:nil];
        //音频播放完成
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
        
        [self _initData];
        
        //设置远程控制事件
        //        [self setRemoteEvent];
        [self createRemoteCommandCenter];
        //歌词时间表与歌词
        _lrcDic = [NSMutableDictionary dictionaryWithCapacity:0];
        _lrcTimeArr = [NSMutableArray arrayWithCapacity:0];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(upDateMusicInfo) name:ShouldPrepareToPlay object:nil];
    }
    
    return self;
}

- (void)_initData{
    //所所有播放音乐信息
    self.allMusicArr = [NSMutableArray array];
    self.cycleType = OrderPlay;
#warning ---Musicdata  根据具体情况去获取所要播放的音乐列表
    NSArray *tempArr = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"songsInfo" ofType:@"plist"]];
    for (int i = 0; i<tempArr.count; i++) {
        NSDictionary *dic = tempArr[i];
        //歌曲信息，根据具体情况修改
        MusicInfo *model = [[MusicInfo alloc] init];
        model.musicName  = dic[@"name"];
        model.musicPath  = dic[@"filename"];
        model.songer     = dic[@"songer"];
        model.icon       = dic[@"icon"];
        model.lrc        = dic[@"lrc"];
        [self.allMusicArr addObject:model];
    }
    if (self.allMusicArr.count>0) {
        self.currentMusic = self.allMusicArr[0];
    }
}

- (void)setRemoteEvent{
    AppDelegate *myAppDel = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    //锁屏后 事件(播放、暂停、上一曲、下一曲)
    /*
     UIEventSubtypeRemoteControlPlay
     UIEventSubtypeRemoteControlPause
     UIEventSubtypeRemoteControlPreviousTrack
     UIEventSubtypeRemoteControlNextTrack
     //耳机上的播放暂停...
     UIEventSubtypeRemoteControlTogglePlayPause
     UIEventSubtypeRemoteControlBeginSeekingBackward
     case UIEventSubtypeRemoteControlEndSeekingBackward
     case UIEventSubtypeRemoteControlBeginSeekingForward
     case UIEventSubtypeRemoteControlEndSeekingForward:
     */
    myAppDel.myRemoteEventBlock = ^(UIEvent *event)
    {
        switch (event.subtype) {
            case UIEventSubtypeRemoteControlPlay:
                [[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool] play];
                break;
            case UIEventSubtypeRemoteControlPause:
                [[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool] pause];
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:
                [[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool] prepareForPlayWithMusic:[self upMusicInfo]];
                [[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool] play];
                break;
            case UIEventSubtypeRemoteControlNextTrack:
                [[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool] prepareForPlayWithMusic:[self nextMusicInfo]];
                [[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool] play];
                break;
                
            default:
                break;
        }
    };
    
}

//锁屏界面开启和监控远程控制事件
- (void)createRemoteCommandCenter{
    /**/
    //远程控制命令中心 iOS 7.1 之后  详情看官方文档：https://developer.apple.com/documentation/mediaplayer/mpremotecommandcenter
    MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
    //   MPFeedbackCommand对象反映了当前App所播放的反馈状态. MPRemoteCommandCenter对象提供feedback对象用于对媒体文件进行喜欢, 不喜欢, 标记的操作. 效果类似于网易云音乐锁屏时的效果
    
    //添加喜欢按钮
    //    MPFeedbackCommand *likeCommand = commandCenter.likeCommand;
    //    likeCommand.enabled = YES;
    //    likeCommand.localizedTitle = @"喜欢";
    //    [likeCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
    //        NSLog(@"喜欢");
    //        return MPRemoteCommandHandlerStatusSuccess;
    //    }];
    //    //添加不喜欢按钮，假装是“上一首”
    //    MPFeedbackCommand *dislikeCommand = commandCenter.dislikeCommand;
    //    dislikeCommand.enabled = YES;
    //    dislikeCommand.localizedTitle = @"上一首";
    //    [dislikeCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
    //        [[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool] prepareForPlayWithMusic:[self upMusicInfo]];
    //        return MPRemoteCommandHandlerStatusSuccess;
    //    }];
    commandCenter.likeCommand.localizedTitle = @"喜欢";
    commandCenter.likeCommand.localizedShortTitle = @"test";
    [commandCenter.likeCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"喜欢");
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    [commandCenter.togglePlayPauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        BOOL isplay = [HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool].isPlaying;
        if (isplay) {
            [[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool] pause];
        }else{
            [[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool] play];
        }
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    [commandCenter.pauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool] pause];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    [commandCenter.playCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool] play];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    [commandCenter.previousTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool] prepareForPlayWithMusic:[self upMusicInfo]];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    [commandCenter.nextTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool] prepareForPlayWithMusic:[self nextMusicInfo]];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    //在控制台拖动进度条调节进度（仿QQ音乐的效果）
    [commandCenter.changePlaybackPositionCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        
        CMTime totlaTime = [HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool].player.currentItem.duration;
        MPChangePlaybackPositionCommandEvent * playbackPositionEvent = (MPChangePlaybackPositionCommandEvent *)event;
        [[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool].player seekToTime:CMTimeMake(totlaTime.value*playbackPositionEvent.positionTime/CMTimeGetSeconds(totlaTime), totlaTime.timescale) completionHandler:^(BOOL finished) {
            double seconds = CMTimeGetSeconds([[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool].player currentTime]);
            [[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool] setCurrentTime:seconds];
        }];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    
}


- (MusicInfo *)upMusicInfo {
    switch (self.cycleType) {
        case SingleCycle:
            return self.currentMusic;
            break;
        case RandomPlay:
            self.currentMusic = self.allMusicArr[arc4random()%self.allMusicArr.count];
            break;
        case OrderPlay:{
            NSInteger index = [self.allMusicArr indexOfObject:self.currentMusic];
            if (index == 0) {
                index = self.allMusicArr.count - 1;
            }else{
                index--;
            }
            self.currentMusic = self.allMusicArr[index];
        }
            break;
            
        default:
            break;
    }
    return self.currentMusic;
}

- (MusicInfo *)nextMusicInfo {
    switch (self.cycleType) {
        case SingleCycle:
            return self.currentMusic;
            break;
        case RandomPlay:
            self.currentMusic = self.allMusicArr[arc4random()%self.allMusicArr.count];
            break;
        case OrderPlay:{
            NSInteger index = [self.allMusicArr indexOfObject:self.currentMusic];
            if (index == self.allMusicArr.count - 1) {
                index = 0;
            }else{
                index++;
            }
            self.currentMusic = self.allMusicArr[index];
        }
            break;
            
        default:
            break;
    }
    return self.currentMusic;
}

- (void)upDateMusicInfo
{
    //解析歌词
    MusicInfo *currentModel = self.currentMusic;
    [self.lrcTimeArr removeAllObjects];
    [self.lrcDic removeAllObjects];
    if (currentModel.lrc.length>0) {
        NSString *str = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:currentModel.lrc ofType:nil] encoding:NSUTF8StringEncoding error:nil];
        NSArray *allRowArr = [str componentsSeparatedByString:@"\n"];
        for (int i = 0; i < allRowArr.count; i++) {
            NSString *linStr = [allRowArr objectAtIndex:i];
            NSArray *lineArray = [linStr componentsSeparatedByString:@"]"];
            if ([lineArray[0] length] > 4) {
                NSString *str1 = [linStr substringWithRange:NSMakeRange(3, 1)];
                NSString *str2 = [linStr substringWithRange:NSMakeRange(6, 1)];
                NSString *str3 = [linStr substringWithRange:NSMakeRange(1, 1)];
                if (([str1 isEqualToString:@":"] && [str2 isEqualToString:@"." ]) || ([str1 isEqualToString:@":"]&&[str2 isEqualToString:@"]"]&&[str3 isEqualToString:@"0"])) {
                    NSString *lrcStr = [lineArray objectAtIndex:1];
                    
                    NSString *timeStr = [[lineArray objectAtIndex:0] substringWithRange:NSMakeRange(1, 5)];//分割区间求歌词时间
                    NSArray *array = [timeStr componentsSeparatedByString:@":"];//把时间转换成秒
                    NSUInteger currentTime = [array[0] intValue] * 60 + [array[1] intValue];
                    NSString *str = [NSString stringWithFormat:@"%ld",currentTime];
                    
                    //把时间 和 歌词 加入词典
                    [self.lrcDic setObject:lrcStr forKey:str];
                    [self.lrcTimeArr addObject:str];//timeArray的count就是行数
                }
                
            }
        }
    }
    
}

#pragma mark -----耳机的监听
- (void)audioRouteChangeListenerCallback:(NSNotification*)notification
{
    NSDictionary *interuptionDict = notification.userInfo;
    NSInteger routeChangeReason = [[interuptionDict valueForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
    switch (routeChangeReason) {
        case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
            NSLog(@"耳机插入");
            break;
        case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
            NSLog(@"耳机拔出，停止播放操作");
            break;
        case AVAudioSessionRouteChangeReasonCategoryChange:
            // called at start - also when other audio wants to play
            NSLog(@"AVAudioSessionRouteChangeReasonCategoryChange");
            break;
    }
    
    [[HD_LiDa_PlayerTool sharedHD_LiDa_PlayerTool] play];
}

#pragma mark  ----- 播放结束
//视频播放到结尾
- (void)playerItemDidReachEnd:(NSNotification *)notification
{
    NSLog(@"播放结束");
}

@end
